<?php 
namespace app\index\controller;

use app\common\model\CompanyStaff;
use app\common\model\CompanyStaffDepart;
use app\common\model\CheckworkRecord;
use app\common\model\CheckworkParam;

class Staff extends Base
{
	/**
	 * 员工信息
	 */
	public function index()
	{
		//获取考勤参数
		$work_param = CheckworkParam::get(1);
		$info = CompanyStaff::get($this->staff_id)->toArray();
		$info['no'] = CompanyStaffDepart::where(['staff_id' => $this->staff_id])->value('no');
		//获取本月开始时间
		$start_time = mktime(0,0,0,date('m'),1,date('Y'));
		//获取本月结束时间
		$end_time = mktime(23,59,59,date('m'),date('t'),date('Y'));
		//获取本月打卡记录
		$month_check = CheckworkRecord::where(['staff_id' => $this->staff_id,'create_time'=>['between',[$start_time,$end_time]]])->select()->toArray();
		$late = 0;  //初始化迟到次数
		$leave = 0; //初始化早退次数
		$normal_work = 0;  //正常考勤
		foreach ($month_check as $rows) {
			$on_time = strtotime($rows['on_time']) ? strtotime($rows['on_time']) : 0;  //上班时间
			$off_time = strtotime($rows['off_time']) ? strtotime($rows['off_time']) : 0; // 下班时间
			$param_on_time = strtotime($work_param->on_time);
			$param_off_time = strtotime($work_param->off_time);
			if($on_time > ($param_on_time + ($work_param->late * 60)))$late ++;
			if($param_off_time > $off_time  && $off_time) $leave++;
			if($on_time < ($param_on_time + ($work_param->late * 60)) && $param_off_time >= $off_time  && $off_time)$normal_work ++;
		}
		$info['late'] = $late;
		$info['leave'] = $leave;
		$info['normal_work'] = $normal_work;
		return $this->success($info);
	}

	/**
	 * 获取员工的打卡记录
	 */
	public function checkRecord()
	{
		//获取客户端传递的时间段
		$times = $this->request->param('times');
		switch ($times) {
			case 0:
				$now_week = date('w');
				if($now_week == 0)$now_week = 7;
				//获取本周开始时间
				$start_time = strtotime(date('Y-m-d').'00:00:00') - ($now_week - 1)*24*60*60;
				//获取本周结束时间
				$end_time = strtotime(date('Y-m-d').'23:59:59') + (7 - $now_week)*24*60*60;
				break;
			case 1:
				//获取上周开始时间
				$start_time = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
				//获取上周结束时间
				$end_time = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
				break;
			case 2:
				//获取本月开始时间
				$start_time = mktime(0,0,0,date('m'),1,date('Y'));
				//获取本月结束时间
				$end_time = mktime(23,59,59,date('m'),date('t'),date('Y'));
				break;
		}
		$list = CheckworkRecord::where(['staff_id' => $this->staff_id,'create_time' => ['between',[$start_time,$end_time]]])->order('id desc')->paginate()->toArray();
		$res = [];
		
		foreach ($list['data'] as $rows) {
			if($rows['off_time']) {
				$item1 = $rows;
				$item1['state'] = 1;
				$item2 = $rows;
				$item2['state'] = 2;
				$res[] = $item1;
				$res[] = $item2;
			} else {
				$item1 = $rows;
				$item1['state'] = 1;
				$res[] = $item1;
			}
		}
		$list['data'] = $res;
		return $this->success($list);
	}
}